﻿using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Data;

namespace SimulationCenter.Data
{
    public class SqlProvider
    {
        private readonly IConfiguration _configuration;

        public SqlProvider(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        private MySqlConnection GetConnection() 
        {
            MySqlConnection conn;
            try
            {
                conn = new MySqlConnection(_configuration.GetConnectionString("Default"));

                if (conn.State != ConnectionState.Open)
                    conn.Open();
            }
            catch (Exception)
            {
                conn = new MySqlConnection(_configuration.GetConnectionString("Default"));
                conn.Open();
            }

            return conn;
        }

        public void Executing(Action<MySqlConnection> action) 
        {
            using (var connection = GetConnection())
            {
                action?.Invoke(connection);
                connection.Close();
            } 
        }
    }
}
